<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="formRules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import { addDepartments, getDepartmentDetail, updateDepartment } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      // 验证用户输入的value值,在整个项目中的编码是否已经存在
      let existCodeList = this.originList.map(item => {
        item.code
      })
      // 过滤掉自己
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (existCodeList.includes(value)) {
        callback(new Error(`当前部门的编码${value}已存在,请换编码`))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      // 验证用户输入的value值,在同级部门不能重复
      // 被占用的列表---->当前点击的部门的子部门
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 编辑时找兄弟
      if (this.isEdit) {
        // 只能获取到当前部门编辑的id,获取当前编辑部门的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 当前部门的pid去找到同级的兄弟,(brother来存放同pid的同级兄弟)
        const brother = this.originList.filter(item => item.pid === pid)
        // 兄弟中除了自己(通过当前的id不等于同级兄弟的id来排除,拿到过滤后的name)
        existNameList = brother.filter(item => item.id !== this.id).map(item => item.name)
      }
      if (existNameList.includes(value)) {
        callback(new Error(`该部门名称${value}已存在,不能重复`))
      } else {
        callback()
      }
    }
    return {
      list: [],
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      formRules: {
        name: [{ validator: validName, trriger: 'blur' }, { required: true, message: '请输入部门名称', trriger: 'blur' }, { min: 1, max: 50, message: '请输入1-50位字符的部门名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入部门编码', trriger: 'blur' }, { min: 1, max: 50, message: '请输入1-50位字符的部门编码', trigger: 'blur' },
          { validator: validCode, trriger: 'blur' }],
        manager: [{ required: true, message: '请输入负责人', trriger: 'change' }],
        introduce: [{ required: true, message: '请输入部门介绍', trriger: 'blur' }, { min: 1, max: 300, message: '请输入1-300位字符的部门介绍', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadEmployeesSimple()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 编辑部门
    async  doEdit() {
      try {
        await updateDepartment(this.form)
        this.$emit('success')
      } catch (error) {
        console.log(error, 'error')
      }
    },
    // 加载部门详情数据,填充到表单中

    async  loadDepartmentDetail() {
      try {
        const res = await getDepartmentDetail(this.id)
        console.log(res, 'res')
        this.form = res.data
      } catch (error) {
        console.log(error, 'error')
      }
    },
    async doAdd() {
      // this.form缺少pid,所以要拿到pid
      try {
        await addDepartments({ pid: this.id, ...this.form })
        // 重新渲染
        // 关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error, 'error')
      }
    },
    async loadEmployeesSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log('getEmployeesSimple', res)
        this.list = res.data
      } catch (error) {
        console.log(error, 'error')
      }
    },
    // 确定
    hSubmit() {
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    //   this.doAdd()
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

